package renguanyu.app.auth4fx.service.user;

import renguanyu.app.auth4fx.dao.user.UserDao;
import renguanyu.app.auth4fx.model.Page;
import renguanyu.app.auth4fx.model.user.UserDto;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class UserService {

    public static Page getUserPage(UserDto userDto){
        Page page = new Page();
        page.setPageCount(countUserPages(userDto));
        page.setPageData(listUsersByPage(userDto));
        return page;
    }

    public static Integer countUserPages(UserDto userDto) {
        String name = userDto.getName();
        String password = userDto.getPassword();
        Integer pageSize = userDto.getPageSize();
        Integer total = UserDao.getUserTotal(name, password);
        Integer totalPage = (total + pageSize - 1) / pageSize;
        return totalPage;
    }

    public static List<Map<String, Object>> listUsersByPage(UserDto userDto) {
        Integer pageSize = userDto.getPageSize();
        Integer currentPageIndex = userDto.getCurrentPageIndex();
        String name = userDto.getName();
        String password = userDto.getPassword();
        Integer limit = pageSize;
        Integer offset = currentPageIndex * pageSize;
        return UserDao.getPagedUsers(limit, offset, name, password);
    }

    public static Integer saveUser(UserDto userDto){
        String name = userDto.getName();
        String password = userDto.getPassword();
        return UserDao.saveUser(name,password);
    }

    public static Integer updateUser(UserDto userDto){
        String id = userDto.getId();
        String name = userDto.getName();
        String password = userDto.getPassword();
        return UserDao.updateUser(name,password,id);
    }

    public static Integer deleteUser(UserDto userDto){
        List<String> ids = userDto.getIds();
        String inSql = ids.stream().map(id -> "?").collect(Collectors.joining(","));
        return UserDao.deleteUser(ids,inSql);
    }

}
